package com.example.interceptors;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.example.utils.JwtUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * Author:yanghua
 * Date:2023/11/2 11:05
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 令牌验证
        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> claims = JwtUtil.parseToken(token);
            // 放行
            return true;
        } catch (Exception e) {
            // 构建响应JSON
            JSONObject jsonResponse = new JSONObject();
            jsonResponse.put("code", 401);
            String jsonResponseStr = JSON.toJSONString(jsonResponse, SerializerFeature.WriteMapNullValue);
            response.getWriter().print(jsonResponseStr);
            // 不放行
            return false;
        }
    }
}
